package com.sadam.ui4.FragmentSelfPage.FragmentComposition;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.sadam.ui4.ActivityLogin;
import com.sadam.ui4.Data.MySqLiteOpenHelper;
import com.sadam.ui4.Data.User;
import com.sadam.ui4.Data.Video;
import com.sadam.ui4.FragmentSelfPage.FragmentPersonalVideoPlayer;
import com.sadam.ui4.MainActivity;
import com.sadam.ui4.R;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class FragmentLikedVideos extends Fragment {

    private static final String TAG = "FragmentLikedVideos";
    private RecyclerView recyclerView;
    private VideoAdapter adapter;
    private List<Video> videoList = new ArrayList<>();
    private boolean isDataLoaded = false;
    private boolean isLoading = false;

    // 添加数据缓存和时间戳
    private long lastLoadTime = 0;
    private static final long LOAD_CACHE_TIME = 30000; // 30秒缓存

    // 线程管理
    private ExecutorService executorService;
    private Future<?> loadTask;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "onCreate");

        // 创建单线程执行器，避免重复任务
        executorService = Executors.newSingleThreadExecutor();
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        Log.d(TAG, "onAttach");
        // 移除了 dbHelper 的初始化
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        Log.d(TAG, "onCreateView");
        View view = inflater.inflate(R.layout.fragment_composition, container, false);

        // 初始化 RecyclerView 和 Adapter
        recyclerView = view.findViewById(R.id.recycler_view_videos);

        adapter = new VideoAdapter(videoList, requireContext());

        // 设置点击事件
        adapter.setOnVideoClickListener((video, position) -> {
            openVideoPlayer(video, position);
        });

        recyclerView.setLayoutManager(new GridLayoutManager(requireContext(), 2));
        recyclerView.setAdapter(adapter);

        return view;
    }

    /**
     * 打开视频播放器
     */
    private void openVideoPlayer(Video video, int position) {
        if (videoList.isEmpty()) {
            Toast.makeText(requireContext(), "暂无视频可播放", Toast.LENGTH_SHORT).show();
            return;
        }

        FragmentPersonalVideoPlayer player = FragmentPersonalVideoPlayer.newInstance(videoList, position, true);
        if (getActivity() != null) {
            player.show(getActivity().getSupportFragmentManager(), "personal_video_player");
        }
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        Log.d(TAG, "onViewCreated");

        // 在视图创建完成后延迟加载数据
        new Handler(Looper.getMainLooper()).postDelayed(() -> {
            if (isAdded() && !isDataLoaded && !isLoading) {
                loadLikedVideos();
            }
        }, 200);
    }

    /**
     * 获取数据库帮助器实例
     */
    private MySqLiteOpenHelper getDbHelper() {
        if (getActivity() instanceof MainActivity) {
            return ((MainActivity) getActivity()).getMySqLiteOpenHelper();
        }
        return null;
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.d(TAG, "onResume, isDataLoaded=" + isDataLoaded);

        if (!isDataLoaded && !isLoading && isResumed()) {
            loadLikedVideos();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        Log.d(TAG, "onPause");

        // 暂停时取消加载任务
        cancelLoadingTask();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        Log.d(TAG, "onDestroyView");

        // 取消正在进行的加载任务
        cancelLoadingTask();

        // 清理资源
        clearResources();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy");

        // 关闭线程池
        shutdownExecutor();
    }

    /**
     * 取消加载任务
     */
    private void cancelLoadingTask() {
        if (loadTask != null && !loadTask.isCancelled()) {
            loadTask.cancel(true);
            Log.d(TAG, "加载任务已取消");
        }
        isLoading = false;
    }

    /**
     * 清理资源
     */
    private void clearResources() {
        if (adapter != null) {
            adapter.clear();
        }
        if (videoList != null) {
            videoList.clear();
        }

        // 释放RecyclerView引用
        if (recyclerView != null) {
            recyclerView.setAdapter(null);
        }
    }

    /**
     * 关闭线程池
     */
    private void shutdownExecutor() {
        if (executorService != null && !executorService.isShutdown()) {
            executorService.shutdownNow();
            Log.d(TAG, "线程池已关闭");
        }
    }

    /**
     * 优化后的加载方法 - 添加防重复加载
     */
    public void loadLikedVideos() {
        Log.d(TAG, "开始加载点赞视频，当前状态: isLoading=" + isLoading);

        // 检查是否正在加载
        if (isLoading) {
            Log.d(TAG, "正在加载中，跳过重复请求");
            return;
        }

        // 检查Fragment状态
        if (!isAdded() || getActivity() == null || isDetached()) {
            Log.w(TAG, "Fragment未附加到Activity，取消加载");
            return;
        }

        // 取消之前的加载任务
        cancelLoadingTask();

        // 检查缓存时间
        long currentTime = System.currentTimeMillis();
        if (isDataLoaded && (currentTime - lastLoadTime) < LOAD_CACHE_TIME) {
            Log.d(TAG, "使用缓存数据，跳过加载");
            return;
        }

        isLoading = true;
        Log.d(TAG, "设置isLoading=true");

        // 显示加载状态
        showLoadingState();

        // 使用ExecutorService管理任务
        loadTask = executorService.submit(() -> {
            try {
                Log.d(TAG, "后台任务开始执行");

                // 检查线程是否被中断
                if (Thread.currentThread().isInterrupted()) {
                    Log.d(TAG, "任务被中断，退出");
                    return;
                }

                // ✅ 获取 dbHelper 并检查
                MySqLiteOpenHelper localDbHelper = getDbHelper();
                if (localDbHelper == null) {
                    Log.e(TAG, "无法获取数据库帮助器实例");
                    requireActivity().runOnUiThread(() -> {
                        if (isAdded()) {
                            handleLoadError("数据库初始化失败，请稍后重试");
                        }
                    });
                    return;
                }

                // ✅ 获取当前用户
                User currentUser = ActivityLogin.getCurrentUserFromSharedPrefrences(requireContext(), localDbHelper);
                if (currentUser == null) {
                    Log.d(TAG, "当前用户未登录，无法加载点赞视频");
                    requireActivity().runOnUiThread(() -> {
                        if (isAdded()) {
                            handleEmptyData("用户未登录");
                        }
                    });
                    return;
                }

                // 从数据库获取点赞视频
                List<Video> likedVideos = localDbHelper.getLikedVideosByUser(currentUser); // ✅ 使用 localDbHelper
                Log.d(TAG, "从数据库获取到 " + (likedVideos != null ? likedVideos.size() : 0) + " 个点赞视频");

                // 检查任务是否被中断
                if (Thread.currentThread().isInterrupted()) {
                    Log.d(TAG, "任务被中断，退出UI更新");
                    return;
                }

                // 更新UI
                updateUIOnMainThread(likedVideos);

            } catch (Exception e) {
                Log.e(TAG, "加载点赞视频失败", e);
                requireActivity().runOnUiThread(() -> {
                    if (isAdded()) {
                        handleLoadError("加载失败: " + e.getMessage());
                    }
                });
            }
        });
    }

    /**
     * 刷新赞过视频列表（强制从数据库重新加载）
     */
    public void refreshLikedVideos() {
        Log.d(TAG, "开始强制刷新赞过视频列表");

        // 重置所有状态，确保重新加载
        isDataLoaded = false;
        lastLoadTime = 0;

        // 清空当前列表
        if (videoList != null) {
            videoList.clear();
        }

        // 通知适配器数据已清空
        if (adapter != null) {
            adapter.notifyDataSetChanged();
        }

        // 重新加载数据
        loadLikedVideos();

        Log.d(TAG, "强制刷新赞过视频列表完成");
    }

    /**
     * 在主线程更新UI
     */
    private void updateUIOnMainThread(List<Video> likedVideos) {
        requireActivity().runOnUiThread(() -> {
            if (!isAdded() || isDetached()) {
                Log.w(TAG, "Fragment已分离，取消UI更新");
                return;
            }

            try {
                Log.d(TAG, "开始更新UI，视频数量: " + (likedVideos != null ? likedVideos.size() : 0));

                // 清空现有数据
                videoList.clear();

                // 添加新数据
                if (likedVideos != null && !likedVideos.isEmpty()) {
                    videoList.addAll(likedVideos);

                    // 限制显示数量，避免内存溢出
                    if (videoList.size() > 50) {
                        videoList = new ArrayList<>(videoList.subList(0, 50));
                        Log.w(TAG, "视频数量过多，限制显示前50个");
                    }
                }

                // 通知适配器更新
                if (adapter != null) {
                    adapter.notifyDataSetChanged();
                    Log.d(TAG, "适配器已更新");
                }

                // 更新状态
                isDataLoaded = true;
                lastLoadTime = System.currentTimeMillis();
                isLoading = false;

                // 显示结果提示
                showResultMessage(likedVideos);

                Log.d(TAG, "UI更新完成");

            } catch (Exception e) {
                Log.e(TAG, "更新UI失败", e);
                isLoading = false;
                Toast.makeText(requireContext(), "更新界面失败", Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * 显示加载状态
     */
    private void showLoadingState() {
        if (isAdded()) {
            // 可以在这里显示进度条等加载状态
            Log.d(TAG, "显示加载状态");
        }
    }

    /**
     * 显示结果消息
     */
    private void showResultMessage(List<Video> likedVideos) {
        if (!isAdded()) return;

        if (likedVideos != null && !likedVideos.isEmpty()) {
            Toast.makeText(requireContext(),
                    "加载了 " + likedVideos.size() + " 个点赞视频",
                    Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(requireContext(),
                    "暂无点赞视频",
                    Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 处理空数据
     */
    private void handleEmptyData(String message) {
        Log.d(TAG, "处理空数据: " + message);
        try {
            if (videoList != null) {
                videoList.clear();
            }
            if (adapter != null) {
                adapter.notifyDataSetChanged();
            }
            isLoading = false;
            Toast.makeText(requireContext(), message, Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            Log.e(TAG, "处理空数据失败", e);
            isLoading = false;
        }
    }

    /**
     * 处理加载错误
     */
    private void handleLoadError(String message) {
        Log.e(TAG, "处理加载错误: " + message);
        try {
            isLoading = false;
            Toast.makeText(requireContext(), message, Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            Log.e(TAG, "处理加载错误失败", e);
            isLoading = false;
        }
    }

    /**
     * 手动刷新（向后兼容）
     */
    public void refresh() {
        Log.d(TAG, "手动刷新");
        refreshLikedVideos();
    }

    /**
     * 强制刷新，忽略缓存（向后兼容）
     */
    public void forceRefresh() {
        Log.d(TAG, "强制刷新");
        refreshLikedVideos();
    }

    /**
     * 获取当前加载状态
     */
    public boolean isLoading() {
        return isLoading;
    }

    /**
     * 获取数据加载状态
     */
    public boolean isDataLoaded() {
        return isDataLoaded;
    }

}